package com.kws.merchant.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.core.domain.R;
import com.kws.common.security.auth.AuthUtil;
import com.kws.common.security.utils.SecurityUtils;
import com.kws.merchant.domain.*;
import com.kws.merchant.domain.po.*;
import com.kws.merchant.domain.vo.ConfirmGoodsVo;
import com.kws.merchant.domain.vo.ConfirmOrderVo;
import com.kws.merchant.domain.vo.ContractOrderVo;
import com.kws.merchant.domain.vo.SignContractVo;
import com.kws.merchant.mapper.DeviceMapper;
import com.kws.merchant.mapper.ItemSchemeMapper;
import com.kws.merchant.mapper.UserOrderMapper;
import com.kws.merchant.service.*;
import com.kws.merchant.util.FileUtil;
import com.kws.merchant.util.HttpContextUtils;
import com.kws.merchant.util.IPUtils;
import com.kws.merchant.util.RedisLockService;
import com.kws.system.api.RemotePaymentService;
import com.kws.system.api.domain.Rq.AlipayWebRq;
import com.kws.system.api.domain.Rq.CreateWeixinPayOrderRq;
import com.kws.system.api.domain.SignFlowRevoke;
import com.kws.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author : zhangbenting
 * @date : 2024/11/5 15:02
 * @Version: 1.0
 */
@Service
public class UserOrderServiceImpl extends ServiceImpl<UserOrderMapper, Order> implements UserOrderService {


    @Autowired
    private ShippingAddressService shippingAddressService;

    @Autowired
    private SpecificationService specificationService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private ShopCartService shopCartService;

    @Autowired
    private RedisLockService redisLockService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RefundLogService refundLogService;

    @Autowired
    private ContractService contractService;

//    @Autowired
//    @Lazy
//    private RemotePaymentService remotePaymentService;

//    private static final long ORDER_TIMEOUT = 30 * 60 * 1000; // 30分钟

    @Override
    public ConfirmOrderVo getConfirmOrder(ConfirmGoodsVo confirmGoodsVo) {
        ConfirmOrderVo confirmOrderVo = new ConfirmOrderVo();
        //获取商品确认单信息
        ConfirmGoodsVo confirmOrderInfo = baseMapper.getConfirmOrderInfo(confirmGoodsVo.getGoodsId(), confirmGoodsVo.getSpecificationId());
        if (ObjectUtils.isNull(confirmOrderInfo)) {
            throw new RuntimeException("商品不存在");
        }
        Integer goodsCount = confirmGoodsVo.getGoodsCount();
        confirmOrderInfo.setGoodsCount(goodsCount);
        BigDecimal price = confirmOrderInfo.getPrice().multiply(BigDecimal.valueOf(goodsCount))
                .setScale(2, RoundingMode.HALF_UP);
        confirmOrderInfo.setPrice(price);
        if (ObjectUtils.isEmpty(confirmOrderInfo.getSpecificationImg())) {
            confirmOrderInfo.setShowImg(FileUtil.fixFileName() + confirmOrderInfo.getImg());
        } else {
            confirmOrderInfo.setShowImg(FileUtil.fixFileName() + confirmOrderInfo.getSpecificationImg());
        }
        List<ConfirmGoodsVo> confirmGoodsVos = new ArrayList<>();
        confirmGoodsVos.add(confirmOrderInfo);
        //获取用户收货地址
        List<ShippingAddress> shippingAddressList = shippingAddressService.list(Wrappers.<ShippingAddress>lambdaQuery()
                .eq(ShippingAddress::getUserId, SecurityUtils.getUserId()));
        if (shippingAddressList != null && shippingAddressList.size() > 0) {
            ShippingAddress address = shippingAddressList.stream().filter(p -> p.getIsDefault().equals(0)).findFirst().orElse(shippingAddressList.get(0));
            confirmOrderVo.setShipAddressList(address);
        }
        confirmOrderVo.setGoodsItemList(confirmGoodsVos);
        return confirmOrderVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Order> addUserOrder(UserOrderPo userOrderPo) {

        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();

        // 获取商品信息列表
        List<ConfirmGoodsPo> confirmGoodsPoList = userOrderPo.getConfirmGoodsPoList();

        // 获取收货地址
        ShippingAddress shipAddress = shippingAddressService.getOne(Wrappers.<ShippingAddress>lambdaQuery()
                .eq(ShippingAddress::getId, userOrderPo.getMemberReceiveAddressId()));

        // 用于存储生成的订单列表
        List<Order> orders = new ArrayList<>();

        //设备商品
        if (CollectionUtil.isNotEmpty(confirmGoodsPoList)) {
            List<Long> deviceIds = confirmGoodsPoList.stream()
                    .map(ConfirmGoodsPo::getGoodsId)
                    .collect(Collectors.toList());

            String deviceIdsStr = CollectionUtil.join(deviceIds, ",");
            List<ConfirmGoodsVo> deviceInfoList = baseMapper.getDeviceInfoList(deviceIdsStr);

            // 判断商品库存
            if (!hasStock(userOrderPo, deviceIds)) {
                throw new RuntimeException("库存不足，无法下单");
            }

            // 获取规格信息
            List<Long> specificationIds = deviceInfoList.stream()
                    .map(ConfirmGoodsVo::getSpecificationId)
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());

            Map<Long, Specification> specificationMap = new HashMap<>();

            if (specificationIds.size() > 0) {
                List<Specification> specificationList = specificationService.list(Wrappers
                        .<Specification>lambdaQuery()
                        .in(Specification::getId, specificationIds));
                specificationMap = specificationList.stream()
                        .collect(Collectors.toMap(Specification::getId, Function.identity()));
            }

            Map<Long, ConfirmGoodsVo> deviceInfoMap = deviceInfoList.stream()
                    .collect(Collectors.toMap(ConfirmGoodsVo::getGoodsId, Function.identity()));

            // 总金额计算
            BigDecimal allPrice = BigDecimal.ZERO;

            //订单编号
            long orderNo = IdWorker.getId();

            for (ConfirmGoodsPo confirmGoodsPo : confirmGoodsPoList) {
                long orderId = IdWorker.getId();
                String lockKey = "order_lock:" + orderId;
                String lockValue = userId.toString();

                // 尝试获取锁
                try {
                    if (!redisLockService.acquireLock(lockKey, lockValue, 8000)) {
                        // 如果获取锁失败，返回 false
                        throw new RuntimeException("获取锁失败！");
                    }

                    Long goodsId = confirmGoodsPo.getGoodsId();
                    ConfirmGoodsVo goodsInfo = deviceInfoMap.get(goodsId);
                    if (goodsInfo == null) {
                        throw new RuntimeException("商品不存在");
                    }

                    // 获取商品规格信息
                    Specification specification = specificationMap.get(confirmGoodsPo.getSpecificationId());

                    // 扣减库存
                    deductInventory(goodsId, confirmGoodsPo.getGoodsCount());

                    // 创建订单
                    Order order = new Order();
                    order.setId(orderId);
                    order.setOrderNo("SD" + String.valueOf(orderNo));
                    order.setUserId(userId);
                    order.setGoodsId(goodsInfo.getGoodsId());
                    BigDecimal money = goodsInfo.getPrice().multiply(new BigDecimal(confirmGoodsPo.getGoodsCount()))
                            .setScale(2, RoundingMode.HALF_UP);
                    order.setOrderPrice(money);
                    order.setGoodsName(goodsInfo.getGoodsName());
                    order.setGoodsImg(goodsInfo.getImg());
                    order.setMerchantId(goodsInfo.getMerchantId());
                    order.setGoodsCount(confirmGoodsPo.getGoodsCount());
                    order.setOrderPrice(goodsInfo.getPrice());
                    order.setLeaveWord(confirmGoodsPo.getLeaveWord());
                    order.setType(0);
                    order.setEnable("1");
                    if (specification != null) {
                        order.setGoodsColor(specification.getColor());
                        order.setSpecificationModel(specification.getSpecificationModel());
                        order.setGoodsImg(specification.getImg());
                    }
                    order.setConsignee(shipAddress.getConsignee());
                    order.setConsigneePhone(shipAddress.getConsigneePhone());
                    order.setAddress(shipAddress.getAddr() + shipAddress.getAddressInfo());
                    order.setShippingAddressId(shipAddress.getId());
                    order.setStatus(0);
                    order.setIsEvaluate(0);
                    order.setProjectType(userOrderPo.getStationType());
                    order.setItemId(Long.valueOf(userOrderPo.getStationId()));
                    // 累加总金额
                    allPrice = allPrice.add(money);

                    // 添加订单到订单列表
                    orders.add(order);

                    // 将订单状态缓存到 Redis，设置过期时间
                    redisTemplate.opsForValue().set("order:" + orderId, String.valueOf(orderId), 72, TimeUnit.HOURS);

                } catch (Exception e) {
                    // 异常处理：记录日志并抛出异常
                    throw new RuntimeException("下单失败：" + e.getMessage());
                } finally {
                    // 释放锁
                    redisLockService.releaseLock(lockKey, lockValue);
                }
            }
            // 保存订单
            this.saveBatch(orders);

            HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
            String ip = IPUtils.getIpAddr(request);

            // 调用支付接口
            switch (userOrderPo.getPayWay()) {
                case 0:
                    //银联支付
                    return orders;
                case 1:
//                    CreateWeixinPayOrderRq rq = new CreateWeixinPayOrderRq();
//                    rq.setOrderNo(String.valueOf(orderNo));
//                    rq.setDescription("商品购买");
//                    rq.setAmount(1);
//                    rq.setType("NATIVE");
////            rq.setAmount(allPrice);
//                    rq.setPayerClientIp(ip);
//                    //微信支付
//                    if (userOrderPo.getPayType() == 0) {
//                        R weixinWebPayOrder = remotePaymentService.createWeixinWebPayOrder(rq);
//                        String data = (String) weixinWebPayOrder.getData();
//                        return data;
//                    } else if (userOrderPo.getPayType() == 1) {
//                        R weixinH5PayOrder = remotePaymentService.createWeixinH5PayOrder(rq);
//                        String data = (String) weixinH5PayOrder.getData();
//                        return data;
//                    } else {
//                        throw new RuntimeException("支付类型错误");
//                    }
                    return orders;
                case 2:
//                    //支付宝支付
//                    AlipayWebRq alipayWebRq = new AlipayWebRq();
//                    alipayWebRq.setOrderNo(String.valueOf(orderNo));
//                    alipayWebRq.setAmount(allPrice);
//                    alipayWebRq.setSubject("商品购买");
//                    R alipayWebOrder = remotePaymentService.alipayWebOrder(alipayWebRq);
//                    String data = (String) alipayWebOrder.getData();
//                    return data;
                    return orders;
                default:
                    throw new RuntimeException("支付方式错误");
            }
        }
        return null;
    }

//    @Scheduled(fixedRate = 2 * 60 * 1000)  // 每 2 分钟执行一次
//    public void checkAndCancelExpiredOrders() {
//        // 获取 Redis 中所有状态为 "created" 的订单
//        Set<String> orderKeys = redisTemplate.keys("order" + "*:status");
//
//        for (String orderKey : orderKeys) {
//            String orderStatus = redisTemplate.opsForValue().get(orderKey);
//            if ("created".equals(orderStatus)) {
//                // 获取订单ID
//                Long orderId = Long.parseLong(orderKey.split(":")[1]);
//
//                // 检查订单是否过期
//                if (isOrderExpired(orderId)) {
//                    // 更新订单状态为已取消（假设状态码为 4）
//                    boolean updated = this.cancelOrder(orderId);
//                    if (updated) {
//                        // 如果订单状态更新成功，可以将 Redis 中的状态也更新
//                        redisTemplate.delete(orderKey);
//                    }
//                }
//            }
//        }
//    }

    /**
     * 取消订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Long orderId) {
        Order byId = this.getById(orderId);
        if (byId == null) {
            throw new RuntimeException("订单不存在");
        }
        if (byId.getStatus() == 5) {
            throw new RuntimeException("订单已被取消，请勿重复操作");
        }
        if (byId.getType().equals(0)){
            //返库存
            Device deviceById = deviceService.getById(byId.getGoodsId());
            deviceById.setInventory(deviceById.getInventory() + byId.getGoodsCount());
            deviceService.saveOrUpdate(deviceById);
        }
        //todo 合同作废
        LambdaQueryWrapper<Contract> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Contract::getOrderId, orderId);
        Contract contractEntity = contractService.getOne(wrapper);
        if (ObjectUtils.isNotNull(contractEntity)){
            SignFlowRevoke signFlowRevoke = new SignFlowRevoke();
            signFlowRevoke.setSignFlowId(contractEntity.getSignFlowId());
            signFlowRevoke.setRevokeReason("取消签订");
            contractService.signFlowRevoke(signFlowRevoke);
        }
        // 5代表已取消状态
        byId.setStatus(5);
//        int updated = baseMapper.updateOrderStatus(orderId, 5);
        if (this.saveOrUpdate(byId)) {
            redisTemplate.delete("order:" + orderId);
            return true;
        }
        return false;
    }

    @Override
    public Page<Order> getUserOrderList(OrderInfoPo orderInfoPo) {
        Page<Order> orderPage = new Page<>(orderInfoPo.getPageSize(), orderInfoPo.getTotalPage());
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        String intervalTime = orderInfoPo.getIntervalTime();
        LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Order::getUserId, userId);
        wrapper.in(ObjectUtils.isNotEmpty(orderInfoPo.getStatus()), Order::getStatus, orderInfoPo.getStatus());
        wrapper.like(ObjectUtils.isNotEmpty(orderInfoPo.getId()), Order::getId, orderInfoPo.getId());
        wrapper.eq(ObjectUtils.isNotEmpty(orderInfoPo.getType()), Order::getType, orderInfoPo.getType());
        wrapper.eq(ObjectUtils.isNotEmpty(orderInfoPo.getIsEvaluate()), Order::getIsEvaluate, orderInfoPo.getIsEvaluate());
        wrapper.eq(ObjectUtils.isNotEmpty(orderInfoPo.getGoodsName()), Order::getGoodsName, orderInfoPo.getGoodsName());
        wrapper.eq(Order::getEnable, "1");
        wrapper.orderByDesc(Order::getCreateTime);
        if (StringUtils.isNotEmpty(intervalTime)) {
            if ("0".equals(intervalTime)) {
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_MONTH, -90);
                wrapper.between(Order::getCreateTime, calendar.getTime(), new Date());
            } else if ("1".equals(intervalTime)) {
                Calendar calendar = Calendar.getInstance();
                calendar.set(Calendar.DAY_OF_YEAR, 1);
                wrapper.ge(Order::getCreateTime, calendar.getTime());
            } else {
                throw new RuntimeException("时间参数错误");
            }
        }
        Page<Order> page = this.page(orderPage, wrapper);
        List<Order> records = page.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (Order record : records) {
                if (StringUtils.isNotEmpty(record.getGoodsImg())) {
                    record.setGoodsImg(FileUtil.fixFileName() + record.getGoodsImg());
                }
            }
        }
        return page;
    }

    @Override
    public String payUserOrder(Long orderId) {
        if (orderId == null) throw new RuntimeException("订单ID不能为空");
        LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Order::getId, orderId);
        Order order = this.getOne(wrapper);
        //todo 调取支付接口

        return "";
    }

    @Override
    public boolean applyRefund(Long orderId) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Order::getOrderNo, orderId);
        Order order = this.getOne(wrapper);
        if (ObjectUtils.isNull()) throw new RuntimeException("订单不存在");
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("申请售后人错误！");
        }
        order.setStatus(2);
        this.updateById(order);

        //新增退款日志
        RefundLogEntity refundLogEntity = new RefundLogEntity();
        //todo 调取支付模块退款接口

        return refundLogService.save(refundLogEntity);
    }

    @Override
    public boolean deleteOrder(Long orderId) {
        SysUser sysUser = AuthUtil.getLoginUser().getSysUser();
        Long userId = sysUser.getUserId();
        LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Order::getId, orderId);
        wrapper.eq(Order::getUserId, userId);
        wrapper.eq(Order::getEnable, "1");
        Order one = this.getOne(wrapper);
        if (ObjectUtils.isNotNull(one)) {
            one.setEnable("0");
            return this.updateById(one);
        } else {
            throw new RuntimeException("该订单已删除");
        }
    }


    @Override
    public boolean updateUserOrder(OrderInfoPo orderInfoPo) {
        Long id = orderInfoPo.getId();
        Order order = this.getById(id);
        if (ObjectUtils.isNotNull(order)) {
            Long shippingAddressId = orderInfoPo.getShippingAddressId();
            ShippingAddress shippingAddress = shippingAddressService.getById(shippingAddressId);
            order.setShippingAddressId(shippingAddressId);
            order.setConsigneePhone(shippingAddress.getConsigneePhone());
            order.setConsignee(shippingAddress.getConsignee());
            order.setAddress(shippingAddress.getAddr() + shippingAddress.getAddressInfo());
            return this.updateById(order);
        }
        return false;
    }

    @Override
    public SignContractVo userSignContract(Long orderId) {
        LambdaQueryWrapper<Contract> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Contract::getOrderId, orderId);
        Contract contractEntity = contractService.getOne(wrapper);
        SignContractVo signContractVo = new SignContractVo();
        if (ObjectUtils.isNotNull(contractEntity)){
            Long contractId = contractEntity.getId();
            SignLinkPo signLinkPo = new SignLinkPo();
            signLinkPo.setContractId(contractId);
            signLinkPo.setType(1);
            Object o = contractService.signLink(signLinkPo);
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(o));
            signContractVo.setContractUrl(jsonObject.getString("url"));
            return signContractVo;
        }
        return signContractVo;
    }

//    @Override
//    public Page<ContractOrderVo> getContractUserOrder(OrderInfoPo orderInfoPo) {
//        //获取用户接受报价
//        Long userId = SecurityUtils.getUserId();
//        orderInfoPo.setPageSize((orderInfoPo.getPageSize() - 1) * orderInfoPo.getTotalPage());
//        Long count = baseMapper.getContractUserOrderCount(userId, orderInfoPo.getId());
//        Page<ContractOrderVo> contractOrderVoPage = new Page<>(orderInfoPo.getPageSize(), orderInfoPo.getTotalPage(), count);
//        if (count > 0) {
//            List<ContractOrderVo> contractUserOrder = baseMapper.getContractUserOrder(userId, orderInfoPo.getId());
//            contractOrderVoPage.setRecords(contractUserOrder);
//        }
//        return contractOrderVoPage;
//    }
//
//    /**
//     * 判断订单是否过期
//     */
//    private boolean isOrderExpired(Long orderId) {
//
//        Long orderCreateTime = getOrderCreateTimeFromRedis(orderId);  // 从 Redis 获取订单创建时间（例如，存储为 UNIX 时间戳）
//
//        if (orderCreateTime == null) {
//            return false;  // 如果订单没有找到创建时间，返回 false
//        }
//
//        long currentTime = System.currentTimeMillis();
//        return currentTime - orderCreateTime > ORDER_TIMEOUT;
//    }

    /**
     * 从 Redis 获取订单的创建时间
     */
    private Long getOrderCreateTimeFromRedis(Long orderId) {
        String key = "order:" + orderId + ":createTime";
        String createTimeStr = redisTemplate.opsForValue().get(key);
        if (createTimeStr != null) {
            return Long.parseLong(createTimeStr);
        }
        return null;
    }

    @Override
    public ConfirmOrderVo getShopCarConfirmOrder(ShopCartPo shopCartPo) {
        List<Long> shopsIds = shopCartPo.getShopsIds();
        List<ShopCartEntity> shopCartEntityList = shopCartService.list(Wrappers.<ShopCartEntity>lambdaQuery().in(ShopCartEntity::getId, shopsIds));
        if (ObjectUtils.isNull(shopCartEntityList)) throw new RuntimeException("购物车商品不存在");
        Map<Integer, List<ShopCartEntity>> shopCartMap = shopCartEntityList.stream().collect(Collectors.groupingBy(ShopCartEntity::getType));
        List<ConfirmGoodsVo> confirmGoodsVos = new ArrayList<>();
        //设备
        List<ShopCartEntity> shopCartEntities = shopCartMap.get(0);
        List<Long> deviceIds = shopCartEntities.stream().map(ShopCartEntity::getDeviceId).filter(Objects::nonNull).collect(Collectors.toList());
        List<Long> specificationIds = shopCartEntities.stream().map(ShopCartEntity::getSpecificationId).filter(Objects::nonNull).collect(Collectors.toList());

        List<Specification> specificationList = specificationService
                .list(Wrappers.<Specification>lambdaQuery().in(Specification::getId, specificationIds));
        String deviceIdsStr = CollectionUtil.join(deviceIds, ",");
        List<ConfirmGoodsVo> deviceInfoList = baseMapper.getDeviceInfoList(deviceIdsStr);

        for (ShopCartEntity shopCartEntity : shopCartEntities) {
            ConfirmGoodsVo confirmGoodsVo = deviceInfoList.stream().filter(p -> p.getGoodsId().equals(shopCartEntity.getDeviceId())).findFirst().orElse(null);
            Specification specification = specificationList.stream().filter(p -> p.getId().equals(shopCartEntity.getSpecificationId())).findFirst().orElse(null);
            if (ObjectUtils.isNotNull(specification)) {
                confirmGoodsVo.setColor(specification.getColor());
                confirmGoodsVo.setSpecificationId(specification.getId());
                confirmGoodsVo.setSpecificationModel(specification.getSpecificationModel());
                confirmGoodsVo.setSpecificationImg(specification.getImg());
            }
            confirmGoodsVos.add(confirmGoodsVo);
        }
        ConfirmOrderVo confirmOrderVo = new ConfirmOrderVo();
        //获取用户收货地址
        List<ShippingAddress> shippingAddressList = shippingAddressService.list(Wrappers.<ShippingAddress>lambdaQuery()
                .eq(ShippingAddress::getUserId, SecurityUtils.getUserId()));
        if (shippingAddressList != null && shippingAddressList.size() > 0) {
            ShippingAddress address = shippingAddressList.stream().filter(p -> p.getIsDefault().equals(0)).findFirst().orElse(shippingAddressList.get(0));
            confirmOrderVo.setShipAddressList(address);
        }
        confirmOrderVo.setGoodsItemList(confirmGoodsVos);
        return confirmOrderVo;
    }

    @Transactional
    public boolean deductInventory(Long deviceId, int quantity) {
        Device device = deviceService.getById(deviceId);
        if (device != null) {
            int currentInventory = device.getInventory();
            // 扣减库存
            device.setInventory(currentInventory - quantity);
            deviceService.updateById(device);
            return true;
        }
        return false; // 商品不存在
    }

    public boolean hasStock(UserOrderPo userOrderPo, List<Long> goodsIds) {
        List<Device> deviceList = deviceService.list(Wrappers.<Device>lambdaQuery().in(Device::getId, goodsIds));
        //判断商品是否都有库存
        for (ConfirmGoodsPo confirmGoodsPo : userOrderPo.getConfirmGoodsPoList()) {
            //获取商品库存
            Device device = deviceList.stream().filter(p -> p.getId().equals(confirmGoodsPo.getGoodsId())).findFirst().orElse(null);
            if (ObjectUtils.isNull(device) || device.getInventory() <= 0
                    || device.getInventory() < confirmGoodsPo.getGoodsCount()) {
                return false;
            }
        }
        return true;
    }
}
